package com.qmzy.lab05.controller;

import com.qmzy.lab05.entity.Account;
import com.qmzy.lab05.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("api")
public class LoginController {

    @Autowired
    private IAccountService service;

    @RequestMapping("/toError")
    public String toError(){
        return "error";
    }

    @RequestMapping("/out")
    public String toOut(){
        return "out";
    }

    @RequestMapping("/index")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/into")
    public String login(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
//        System.out.println("进入login里了,"+"authentication:"+authentication);
        User user = (User) authentication.getPrincipal();
        Object[] objects = user.getAuthorities().toArray();
        return objects[0].toString();
    }

    @PostMapping("/check")
    public int check(@RequestBody Map<String,String> mp){
        //防水墙验证
        return TCaptchaVerify.verifyTicket(mp.get("ticket"),mp.get("randstr"));
    }



    @PreAuthorize("hasRole('USER')")
    @RequestMapping("/user")
    public Integer toUser(){
        return 1;
    }

    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/admin")
    public Integer adminPage(){
        return 1;
    }

}
